<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.min.css">
  <script src="./lib/vue-2.5.9.js"></script>
</head>

<body>
  <div id="app">

    <div>

      <label>Id:</label>
      <input type="text" v-model="id">
      <label>Name:</label>
      <input type="text" v-model="name">
      <input type="button" value="添加" class="btn btn-primary" @click="add"> &nbsp;&nbsp;&nbsp;&nbsp; 按照品牌名称检索:
      <input type="text" v-model="keywords" @change="searchByName">

    </div>

    <table class="table table-bordered table-hover table-striped">
      <thead>
        <tr>
          <th>Id</th>
          <th>Name</th>
          <th>CTime</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in searchByName()" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.ctime }}</td>
          <td>
            <a href="http://www.baidu.com" @click.prevent="del(item.id)">删除</a>
          </td>
        </tr>
      </tbody>
    </table>


  </div>

  <script>
    // 创建 Vue 实例，得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        id: '',
        name: '',
        keywords: '', // 根据名称检索时候的关键字
        list: [
          { id: 1, name: '奔驰', ctime: new Date() },
          { id: 2, name: '宝马', ctime: new Date() },
          { id: 3, name: '千里马', ctime: new Date() },
          { id: 4, name: '奔奔', ctime: new Date(), }
        ]
      },
      methods: {
        add() { // 添加
          this.list.push({ id: this.id, name: this.name, ctime: new Date() })
          this.id = this.name = ''
        },
        del(id) { // 点击删除商品
          const index = this.list.findIndex(function (item, i, arr) {
            return item.id == id
          })
          this.list.splice(index, 1)
        },
        searchByName() { // 根据搜索的关键字,检索品牌数据
          // console.log(this.keywords)

          let result = []
          // 循环list中的每一项,拿到这一项之后,判断 名称中,是否包含 关键字,如果包含,则把 这一项,添加到 result 中
          for (let i = 0; i < this.list.length; i++) {
            /* if (this.list[i].name.indexOf(this.keywords) != -1) {
              result.push(this.list[i])
            } */

            if (this.list[i].name.includes(this.keywords)) result.push(this.list[i])
          }

          return result
        }
      }
    });
  </script>
</body>

</html>